export function bindEvents(shadowRoot, state, instance) {
    const items = shadowRoot.querySelectorAll('.interaction-item');
    
    items.forEach(item => {
        item.addEventListener('click', (e) => {
            const action = item.getAttribute('data-action');
            handleAction(action, item, state, instance);
        });
    });
}

export function handleAction(action, element, state, instance) {
    switch (action) {
        case 'like':
            toggleLike(element, state, instance);
            break;
        case 'comment':
            openComments(state, instance);
            break;
        case 'collect':
            toggleCollect(element, state, instance);
            break;
        case 'share':
            openShare(state, instance);
            break;
    }
}

export function toggleLike(element, state, instance) {
    state.liked = !state.liked;
    state.likeCount += state.liked ? 1 : -1;
    
    element.classList.toggle('active', state.liked);
    element.querySelector('.count').textContent = formatCount(state.likeCount);
    
    // 触发点赞动画
    triggerAnimation(element, 'like');
    
    // 派发自定义事件
    instance.dispatchEvent(new CustomEvent('like-changed', {
        detail: { liked: state.liked, count: state.likeCount }
    }));
}

export function toggleCollect(element, state, instance) {
    state.collected = !state.collected;
    state.collectCount += state.collected ? 1 : -1;
    
    element.classList.toggle('active', state.collected);
    element.querySelector('.count').textContent = formatCount(state.collectCount);
    
    // 触发收藏动画
    triggerAnimation(element, 'collect');
    
    // 派发自定义事件
    instance.dispatchEvent(new CustomEvent('collect-changed', {
        detail: { collected: state.collected, count: state.collectCount }
    }));
}

export function openComments(state, instance) {
    // 派发评论事件
    instance.dispatchEvent(new CustomEvent('comment-clicked', {
        detail: { count: state.commentCount }
    }));
}

export function openShare(state, instance) {
    // 派发分享事件
    instance.dispatchEvent(new CustomEvent('share-clicked', {
        detail: { count: state.shareCount }
    }));
}

export function triggerAnimation(element, type) {
    const iconWrapper = element.querySelector('.icon-wrapper');
    
    // 移除之前的动画类
    iconWrapper.classList.remove('animate-like', 'animate-collect');
    
    // 强制重绘
    iconWrapper.offsetHeight;
    
    // 添加动画类
    iconWrapper.classList.add(`animate-${type}`);
    
    // 动画结束后移除类
    setTimeout(() => {
        iconWrapper.classList.remove(`animate-${type}`);
    }, 600);
}

export function formatCount(count) {
    if (count >= 1000000) {
        return (count / 1000000).toFixed(1) + 'M';
    } else if (count >= 1000) {
        return (count / 1000).toFixed(1) + 'K';
    }
    return count.toString();
}